package com.dom.domweb.modular.shiro.service;

import com.dom.domweb.dao.entity.TRoleInfo;
import com.dom.domweb.dao.entity.TUserInfo;
import com.dom.domweb.dao.entity.TUserRoleRel;
import com.dom.domweb.dao.service.ITRoleInfoService;
import com.dom.domweb.dao.service.ITUserInfoService;
import com.dom.domweb.dao.service.ITUserRoleRelService;
import com.dom.domweb.modular.shiro.model.ShiroUser;
import com.dom.util.SpringContextHolder;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 用户认证服务
 * @Author xllei
 * @Date 2018/11/18 8:56 AM
 * @Version 1.0
 **/
@Service
@DependsOn("springContextHolder")
public class UserAuthService {
    @Autowired
    private ITUserInfoService userInfoService;
    @Autowired
    private ITUserRoleRelService userRoleRelService;
    @Autowired
    private ITRoleInfoService roleInfoService;

    public static UserAuthService getInstance(){
        return SpringContextHolder.getBean(UserAuthService.class);
    }

    public TUserInfo getUser(String userName){
        TUserInfo userInfo = userInfoService.getUserByUserName(userName);
        if (userInfo == null) {
            throw new UnknownAccountException("系统中未找到该用户");
        }
        return userInfo;
    }

    public ShiroUser getShiroUser(TUserInfo userInfo) {
        ShiroUser shiroUser = new ShiroUser();
        BeanUtils.copyProperties(userInfo, shiroUser);
        List<TRoleInfo> roleInfos = getRoleInfo(userInfo.getId());
        //赋值用户角色列表
        shiroUser.setRoles(roleInfos.stream().map(TRoleInfo::getId).collect(Collectors.toList()));
        //赋值用户角色名称列表
        shiroUser.setRoleNames(roleInfos.stream().map(TRoleInfo::getRoleName).collect(Collectors.toList()));
        return shiroUser;
    }

    public SimpleAuthenticationInfo info(ShiroUser shiroUser, TUserInfo user, String realmName) {
        String credentials = user.getPasswd();

        // 密码加盐处理
//        String source = user.getSalt();
//        ByteSource credentialsSalt = new Md5Hash(source);
        return new SimpleAuthenticationInfo(shiroUser, credentials, null, realmName);
    }

    /**
     * 获取用户角色信息
     * @param userId
     * @return
     */
    private List<TRoleInfo> getRoleInfo(int userId){
        List<TUserRoleRel> userRoleRels = userRoleRelService.findByUserId(userId);
        List<Integer> roles = userRoleRels.stream().map(TUserRoleRel::getRoleId).collect(Collectors.toList());
        return roleInfoService.selectBatchIds(roles);
    }
}
